package com.ymm.driver.core.listener.mq;

import com.alibaba.fastjson.JSON;
import com.ymm.driver.api.constants.Entity.NoticeEntity;
import com.ymm.driver.api.constants.Entity.OrderOpsLogEntity;
import com.ymm.driver.api.facade.DriverNoticeService;
import com.ymm.driver.api.facade.DriverPersonalAllInformationService;
import com.ymm.driver.api.utils.Result;
import com.ymm.driver.core.constants.MessgeStatusEnum;
import com.ymm.driver.core.constants.NoticeFromPersonEnum;
import com.ymm.driver.core.constants.NoticeTypeEnum;
import com.ymm.driver.core.constants.OrderOpsEnum;
import com.ymm.driver.core.listener.mq.msg.OrderConfirmMsg;
import com.ymm.driver.core.websocket.WebSocket;
import com.ymm.driver.dao.mapper.DriverOrderOpsLogMapper;

//import javafx.scene.chart.ScatterChart;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Objects;

/**
 * @Company: CUG
 * @Description: TODO
 * @Author: LiYangyong
 * @Date: 2022/8/16/016 16:09
 **/
@Slf4j
@Component
@RocketMQMessageListener(topic = "${mq.topic.order}", consumerGroup = "${mq.consumer.groupname.order.confirm}", selectorExpression = "confirm", maxReconsumeTimes = 3)
public class OrderConfirmMQListener implements RocketMQListener<MessageExt> {
    @Resource
    private DriverOrderOpsLogMapper driverOrderOpsLogMapper;

    @Resource
    private DriverNoticeService driverNoticeService;

    @Resource
    private DriverPersonalAllInformationService driverPersonalAllInformationService;

    @Resource
    private WebSocket webSocket;

    @Override
    public void onMessage(MessageExt messageExt) {
        //解析消息内容
        String body = new String(messageExt.getBody(), StandardCharsets.UTF_8);
        OrderConfirmMsg orderConfirmMsg = JSON.parseObject(body, OrderConfirmMsg.class);
        if (Objects.isNull(orderConfirmMsg)) {
            log.info("orderConfirmMsg为空！");
            return;
        }
        Long orderId = orderConfirmMsg.getOrderId();
        Long driverId = orderConfirmMsg.getDriverId();
        Long cargoId = orderConfirmMsg.getCargoId();
        Integer cargoPrice = orderConfirmMsg.getCollectPrice();
        Integer opsType = OrderOpsEnum.CONFIRM.getCode();
        if (Objects.isNull(orderId) || Objects.isNull(driverId) || Objects.isNull(cargoId) || Objects.isNull(cargoPrice)) {
            log.info("参数为空！");
            return;
        }
        OrderOpsLogEntity orderOpsLog = new OrderOpsLogEntity();
        orderOpsLog.setDriverId(driverId);
        orderOpsLog.setOrderId(orderId);
        orderOpsLog.setCargoId(cargoId);
        orderOpsLog.setOpsType(opsType);
        orderOpsLog.setOpsPersonType(orderConfirmMsg.getOpsPersonType());
        orderOpsLog.setOpsPersonId(orderConfirmMsg.getOpsPersonId());
        orderOpsLog.setCreateTime(new Date());
        orderOpsLog.setUpdateTime(new Date());
        orderOpsLog.setExecutionStatus(MessgeStatusEnum.IN_EXECUTION.getCode());


        //保存到数据库
        try {
            driverOrderOpsLogMapper.add(orderOpsLog);
        } catch (Exception e) {
            if (!Objects.isNull(driverOrderOpsLogMapper.getLogIdByDriverIdAndOrderIdAndOpsType(driverId, orderId, opsType))) {
                log.info("消息已经被消费过");
                return;
            } else {
                log.info("数据库错误");
                //重试
                throw e;
            }
        }


        /**
         * 传来的是分  不需要成*00
         */
        try {
            Integer drbillType = 4;
            String description = "司机收款";
            // 将收款更新到账单流水
            driverPersonalAllInformationService.drbillCollectSKPrice(BigInteger.valueOf(orderConfirmMsg.getDriverId()), Double.valueOf(orderConfirmMsg.getCollectPrice().toString()), drbillType, description, BigInteger.valueOf(orderConfirmMsg.getOrderId()));
            // 将收款更新到数据库
            Result<Double> driverProfitById = driverPersonalAllInformationService.getDriverProfitById(BigInteger.valueOf(orderConfirmMsg.getDriverId()));
            Double price = driverProfitById.getData();
            driverPersonalAllInformationService.addDriverProfit(BigInteger.valueOf(orderConfirmMsg.getDriverId()), Double.valueOf(orderConfirmMsg.getCollectPrice().toString()) + price);
        } catch (Exception e) {
            log.info("司机收款失败！重新消费消息");
            e.printStackTrace();
            driverOrderOpsLogMapper.deleteByLogId(orderOpsLog.getLogId());
            throw e;
        }

        //投递通知
        try {
            NoticeEntity notice = new NoticeEntity();
            notice.setDriverId(driverId);
            notice.setContent("您有一笔收款");
            notice.setFromPersonType(NoticeFromPersonEnum.SYSTEM.getCode());
            notice.setFromPersonId(0L);
            notice.setNoticeType(NoticeTypeEnum.CARGO_NOTICE.getCode());
            notice.setAdditionalInformation("{\"orderId\":" + orderId + ", \"cargoId\":" + cargoId + "}");
            driverNoticeService.saveNotice(notice);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //WebSocket通知
        try {
            webSocket.sendOnMessage(driverId, "您有一笔收款");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //设置业务执行状态为完成
        driverOrderOpsLogMapper.updateExecutionStatusByLogId(orderOpsLog.getLogId(), MessgeStatusEnum.COMPLETED.getCode());
    }
}
